package com.wxg.kit;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import com.wxg.util.MyUtils;

public class DownloadRemoteFile {

	public void download(String path){
//		URL url = null;
		try {
			URL url = new URL(path);
			String filename = path.substring( path.lastIndexOf("/")+1 );
			
			File outputFile = new File( MyUtils.tempDir()+"/"+filename );
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outputFile));
			
			InputStream is = url.openConnection().getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			byte[] buffer = new byte[1024]; //2048|1024
			int len = 0;
			while( (len=bis.read(buffer)) != -1 ){
				bos.write(buffer, 0, len);
			}
			bis.close();
			bos.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String fetchRemoteFile(String path) {
		String retStr = null;
		try {
			URL url = new URL(path);
			BufferedInputStream bis = new BufferedInputStream(url.openConnection().getInputStream());
			ByteArrayOutputStream aos = new ByteArrayOutputStream();
			int len = 0;
			byte[] buffer = new byte[1024];
			while( (len=bis.read(buffer)) != -1 ){
				aos.write(buffer, 0, len);
			}
			retStr = aos.toString("utf8");
			bis.close();
			aos.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return retStr;
	}
	
	
}
